import {activateMemberAfterPay, checkMemberAfterPay} from "@src/api/member";
import {
  parseCategoryRights,
  parsePrivileges,
  parseRechargeAwardRule
} from "@src/common/memberCardUtils";
import router from "@src/router";
import {storeBindingsBehavior} from "mobx-miniprogram-bindings";
import member from "@src/store/member";
import base from "@src/store/base";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: member,
    fields: ['isMember', 'memberName', 'phone'],
    actions: ['getBaseInfo'],
  }, {
    store: base,
    fields: ['themeColor', 'themeTitleColor', 'businessLogo', 'businessName']
  }],
  data: {},
  methods: {
    onLoad(options) {
      console.log("activeMineCard.vue接收到的参数", options);
    },
    onLogin() {
      this.fetchData();
    },
    fetchData() {
      checkMemberAfterPay().then(res => {
        if (res.data) {
          let card = res.data;
          let category = card.category;
          let privileges = card.privileges;
          let rechargeAward = card.rechargeAward;
          let categoryRights = parseCategoryRights(category, rechargeAward).concat(parseRechargeAwardRule(rechargeAward))
          privileges = parsePrivileges(privileges);
          this.setData({privileges, categoryRights, category, card: card})
        } else {
          wx.showModal({
            title: "温馨提示",
            content: "暂无待激活的会员卡",
            showCancel: false,
            confirmText: "回首页",
            success(res) {
              if (res.confirm) {
                router.push({name: "index"})
              }
            }
          });
        }
      })
    },
    // 获取手机号
    getPhoneNumber(e) {
      if (!e.detail.iv) {
        wx.showToast({title: "手机号获取失败，请重试", icon: "none", duration: 1500});
        return;
      }
      let data = {
        ivStr: e.detail.iv,
        encryptedData: e.detail.encryptedData,
      }
      this.activeCard(data);
    },
    //激活卡
    activeCard(data) {
      activateMemberAfterPay(data).then(res => {
        if (res.code === 0) {
          this.getBaseInfo();
          wx.showModal({
            title: "温馨提示",
            content: "激活会员成功",
            showCancel: false,
            confirmText: "确定",
            success(res) {
              if (res.confirm) {
                router.push({name: "index"})
              }
            }
          });
        } else {
          wx.showModal({
            title: "温馨提示",
            content: res.code + res.msg,
            confirmText: "回首页",
            success(res) {
              if (res.confirm) {
                router.push({name: "index"})
              }
            }
          });
        }
      })
    }
  }
})
